package com.weibo.api;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.weibo.util.ConfKit;

/**
 * 微博支付
 * @author L.cm
 * email: 596392912@qq.com
 * site:  http://www.dreamlu.net
 * @date 2014-4-15 下午12:39:44
 */
public class WeiBo {

	// 对于微博版本低的，建议他下载
	public static final String _DOWN_APP = "http://mall.sc.weibo.com/h5/temp/nosupport";

	// 配置文件
	public static Map<String, String> props = ConfKit.get("weibo.properties");
	// 默认字符集
	protected static final String DEFAULT_CHARSET = "UTF-8";
	
	/**
	 * 构造签名
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static String initUrl(Map<String, String> params, boolean encode) throws UnsupportedEncodingException {
		Set<String> keysSet = params.keySet();
		Object[] keys = keysSet.toArray();
		Arrays.sort(keys);
		StringBuffer temp = new StringBuffer();
		boolean first = true;
		for (Object key : keys) {
			if (first) {
				first = false;
			} else {
				temp.append("&");
			}
			Object value = params.get(key);
			if (null == value) {
				continue;
			}
			temp.append(key).append("=");
			if (encode) {
				temp.append(URLEncoder.encode(value.toString(), WeiBo.DEFAULT_CHARSET));
			} else {
				temp.append(value.toString());
			}
		}
		return temp.toString();
	}
	
	/**
	 * 判断是否来自微博客户端4.3及以上版本支持微博支付
	 * @param request
	 * @return
	 * 
	 * User-Agent片段： Mobile/11D167 Weibo (iPhone5,3__weibo__4.3.0__iphone__os7.1)
	 */
	public static boolean isWeibo43Up(HttpServletRequest request) {
		String userAgent = request.getHeader("User-Agent");
		if (StringUtils.isNotBlank(userAgent)) {
			Pattern p = Pattern.compile("__weibo__([\\d\\.]{2,3})", Pattern.CASE_INSENSITIVE);
			Matcher m = p.matcher(userAgent);
			String version = null;
			if(m.find()){
				version = m.group(1);
			}
			return NumberUtils.toDouble(version) >= 4.3d;
		}
		return false;
	}
}
